/* 
 * File:   JSVNSock_Stream_InterConversion.cpp
 * Author: johnneyshi
 * 
 * Created on 2013年5月18日, 下午4:37
 */

#include "JSVNSock_Stream_InterConversion.h"
#include "JFile.h"
#include "JSocket.h"

JSVNSock_Stream_InterConversion::JSVNSock_Stream_InterConversion() {
}

JSVNSock_Stream_InterConversion::~JSVNSock_Stream_InterConversion() {
}

void JSVNSock_Stream_InterConversion::SockToStream(int fd, std::string fileName)
{
    //先得到首4个字节，表示要接受到数据的大小，然后保存到文件，然后调用serverStub.AnalysisCommand
    int classSize;
    JSocket::Recv(fd,(char*)&classSize,sizeof(int));
//    cout << "JServerWorkerSVN recv:" << classSize << endl;
    //这是缓冲区文件，也就是服务器接受到数据，先写入这个文件，然后再供repository调用
    JFile file(fileName);
    file.OpenStream(std::ios::binary | std::ios::trunc | std::ios::out);
    int restSize = classSize;
    file.WriteToFile((char*)&classSize,sizeof(int));
    char buff[1024];
    int tmpSize = 0;
    while(restSize > 0)
    {
        if(restSize > 1024)
        {
            tmpSize = 1024;
        }
        else
        {
            tmpSize = restSize;
        }
        tmpSize = JSocket::Recv(fd,buff,tmpSize);
        file.WriteToFile(buff,tmpSize);
        restSize -= tmpSize;
    }
    file.CloseStream();
}

void JSVNSock_Stream_InterConversion::StreamToSock(int fd, std::string fileName)
{
    JFile file(fileName);
    file.OpenStream(std::ios::binary | std::ios::in);
    char buff[1024];
    int n;
    while(!file.fs.eof())
    {
        n = file.fs.readsome(buff,1024);
        if(n == 0)
        {
            break;
        }
        JSocket::Send(fd,buff,n);
    }
    file.CloseStream();
}